package com.dgut.forum.controller;

import com.dgut.forum.common.AppResult;
import com.dgut.forum.common.ResultCode;
import com.dgut.forum.config.AppConfig;
import com.dgut.forum.exception.ApplicationException;
import com.dgut.forum.model.User;

import com.dgut.forum.services.IUserService;
import com.dgut.forum.utils.MD5Util;
import com.dgut.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.security.util.Password;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Api(tags="用户接口")
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController{

    @Autowired
    private IUserService userService;

    @ApiOperation("退出用户登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        request.getSession().invalidate();
        log.info("退出登录成功");
        return AppResult.success(ResultCode.SUCCESS);
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult getUserInfo(HttpServletRequest request,
                                 @ApiParam("用户id") @RequestParam(value = "id",required = false)  Long id){
        User user=null;
        //如果id为空,说明是为了获取到登陆主页的用户信息
        if(id==null) {
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
           user=userService.selectByPrimaryKey(id);
        }

        return AppResult.success(user);
    }
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){

        User user=userService.login(username,password);
        if(user==null){
            log.info("用户 "+username+",不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS ));
        }
        HttpSession session=request.getSession();
        session.setAttribute(AppConfig.USER_SESSION,user);
        return AppResult.success();
    }

    @ApiOperation("注册用户")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
//         if(StringUtil.stringNoLength(username)
//                 ||StringUtil.stringNoLength(nickname)
//                 ||StringUtil.stringNoLength(password)
//                 ||StringUtil.stringNoLength(passwordRepeat)){
//             return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//         }

        if(!password.equals(passwordRepeat)) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME));
        }

        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);

        String salt= UUIDUtil.UUID_32();
        String encrypt= MD5Util.md5Second(password,salt);
        user.setSalt(salt);
        user.setPassword(encrypt);

        //调用服务器创建用户的接口
        userService.createNormalUser(user);
        //没有抛出异常就是成功
        return AppResult.success();
    }

    @ApiOperation("修改用户信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                    @ApiParam("用户名") @RequestParam(value = "username",required = false) String username,
                                    @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                    @ApiParam("电话号码") @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                    @ApiParam("邮箱地址") @RequestParam(value = "email",required = false) String email,
                                    @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                    @ApiParam("用户头像") @RequestParam(value = "avatarUrl",required = false) String avatarUrl,
                                    @ApiParam("个人简介") @RequestParam(value = "remark",required = false) String remark){
        //参数校验
        if(username==null&&nickname==null&&phoneNum==null&&email==null&&gender==null&&avatarUrl==null&&remark==null){
            log.info("修改用户信息,所需的内容全为空");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);

        //构建需要需改的用户信息,后续会校验
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(username);
        updateUser.setNickname(nickname);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setEmail(email);
        updateUser.setGender(gender);
        updateUser.setAvatarUrl(avatarUrl);
        updateUser.setRemark(remark);

        //执行修改
        userService.updateUserInfo(updateUser);

        //更新session中的用户信息
        user=userService.selectByPrimaryKey(user.getId());
        session.setAttribute(AppConfig.USER_SESSION,user);

        return AppResult.success(user);
    }

    @ApiOperation("修改用户密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPwd(HttpServletRequest request,
                                    @ApiParam("旧密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("重复新密码") @RequestParam("passwordRepeat") @NonNull String newRepeatPassword){
        //获取用户信息
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断获取的用户状态
        if(user==null||user.getDeleteState()==1){
            log.info("修改密码,指定用户不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if(!newPassword.equals(newRepeatPassword)){
            log.info("新密码和重复新密码不相同");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_TWO_NEW_PWD_NOT_SAME));
        }

        userService.modifyPassword(user.getId(), oldPassword,newPassword);
        log.info("修改用户成功");
        //修改密码成功,强制重新登陆
        //退出登录
        request.getSession().invalidate();
        log.info("强制重新登录");
        return AppResult.success();
    }
}
